package cn.com.ayqu.module.erp.service.activity;

import cn.com.ayqu.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.com.ayqu.framework.mybatis.core.query.MPJLambdaWrapperX;
import cn.com.ayqu.module.erp.dal.dataobject.activityuser.ActivityUserDO;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.com.ayqu.module.erp.controller.admin.activity.vo.*;
import cn.com.ayqu.module.erp.dal.dataobject.activity.ActivityDO;
import cn.com.ayqu.framework.common.pojo.PageResult;
import cn.com.ayqu.framework.common.pojo.PageParam;
import cn.com.ayqu.framework.common.util.object.BeanUtils;

import cn.com.ayqu.module.erp.dal.mysql.activity.ActivityMapper;

import static cn.com.ayqu.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.com.ayqu.module.erp.enums.ErrorCodeConstants.*;

/**
 * 活动列表 Service 实现类
 *
 * @author 高连杰
 */
@Service
@Validated
public class ActivityServiceImpl implements ActivityService {

    @Resource
    private ActivityMapper activityMapper;

    @Override
    public Long createActivity(ActivitySaveReqVO createReqVO) {
        // 插入
        ActivityDO activity = BeanUtils.toBean(createReqVO, ActivityDO.class);
        activityMapper.insert(activity);
        // 返回
        return activity.getId();
    }

    @Override
    public void updateActivity(ActivitySaveReqVO updateReqVO) {
        // 校验存在
        validateActivityExists(updateReqVO.getId());
        // 更新
        ActivityDO updateObj = BeanUtils.toBean(updateReqVO, ActivityDO.class);
        activityMapper.updateById(updateObj);
    }

    @Override
    public void deleteActivity(Long id) {
        // 校验存在
        validateActivityExists(id);
        // 删除
        activityMapper.deleteById(id);
    }

    private void validateActivityExists(Long id) {
        if (activityMapper.selectById(id) == null) {
            throw exception(ACTIVITY_NOT_EXISTS);
        }
    }

    @Override
    public ActivityDO getActivity(Long id) {
        return activityMapper.selectById(id);
    }

    @Override
    public PageResult<ActivityDO> getActivityPage(ActivityPageReqVO pageReqVO) {
        return activityMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ActivityDO> getUserJoinActivityList(Long userId) {
        return activityMapper.selectList(
                new MPJLambdaWrapperX<ActivityDO>()
                        .rightJoin(ActivityUserDO.class, ActivityUserDO::getActivityId, ActivityDO::getId)
                        .eq(ActivityUserDO::getUserId, userId)
                        .orderByAsc(ActivityUserDO::getCreateTime)
                        .groupBy(ActivityUserDO::getActivityId)
                        .selectAll(ActivityDO.class)
                        .selectAs(ActivityUserDO::getCreateTime, ActivityDO::getCreateTime)
        );
    }

}